const needExchange = (address) => {
   return (address.indexOf('details.php') > -1 || address.indexOf('download.php') > -1)
}

// 从url获取参数
const getUrlParam = (url, name) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = url.substr(url.indexOf('?') + 1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return null;
}

const TorrentUtil = {
    // 判断链接是否需要转换 如详情页地址 -> 种子下载地址
    
    estimateAddress : (address, sites) => {
        // https://kp.m-team.cc/details.php?id=606304&hit=1
        if (needExchange(address)) {
            const id = getUrlParam(address, 'id');
            // 1.获取替换地址
            const site = sites.find(site => {
                return (site.address && (address.indexOf(site.address) > -1));
            });
            if (site && site.passkey && id) {
                address = site.passkey.replace('${id}', id);
            }
        }
        return address;
    },
}

export default TorrentUtil